package edu.cuhk.cs.bookstore.servlet;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import aws.handler.ItemSearchRequestHandler;

import edu.cuhk.cs.bookstore.model.Book;

/**
 * Servlet implementation class AutocompleteBook
 */
public class AutocompleteBook extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AutocompleteBook() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		process(request,response);
	}

	private void process(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		//System.err.println("Start Google ... ");
		String input = request.getParameter("term");
		response.setContentType("text/html;charset=UTF-8");
        //PrintWriter out = response.getWriter();
        
		String result = "[";
		result += listResult(input);
		result += "]";
		//System.out.println("[\"Superman\", \"Agadoo\"]");
		PrintWriter pw = response.getWriter();
		pw.println(result);
		
	}

	private String listResult(String input) {
		/*
		List <Book> books = new ArrayList <Book>();
		books.add(new Book("A Christmas Carol","aaa","bbb","ccc",new Date()));
		books.add(new Book("A streetcar named desire","aaa","bbb","ccc",new Date()));
		books.add(new Book("A Connecticut Yankee In King Arthur's Court","aaa","bbb","ccc",new Date()));
		books.add(new Book("A portrait of the artist as a young man","aaa","bbb","ccc",new Date()));
		books.add(new Book("A Confederacy of Dunces","aaa","bbb","ccc",new Date()));
		books.add(new Book("A Tale of Two Cities","aaa","bbb","ccc",new Date()));
		books.add(new Book("Planting a Rainbow","aaa","bbb","ccc",new Date()));
		books.add(new Book("Sheep in a Jeep","aaa","bbb","ccc",new Date()));
		books.add(new Book("To Kill a Mockingbird","aaa","bbb","ccc",new Date()));
		books.add(new Book("A midsummer-night's dream: Volume 26","aaa","bbb","ccc",new Date()));
		List <Book> books = (new ItemSearchRequestHandler()).searchByTitle(input);
		*/
		
		try {
			input = URLEncoder.encode(input,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		String result = "";
		
		String url = "http://www.google.com/complete/search?output=toolbar&hl=en&q=" + input;

        try {
        	URLConnection httpConnection = new URL(url).openConnection();
            httpConnection.connect();
            BufferedInputStream bis = new BufferedInputStream(httpConnection.getInputStream());

            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (bis);
            NodeList listOfSuggestion = doc.getElementsByTagName("suggestion");
            int totalSuggestion = listOfSuggestion.getLength();
            //System.out.println("Total no of Suggestion : " + totalSuggestion);
            for(int s=0; s<listOfSuggestion.getLength() ; s++){
                Node firstSuggestionNode = listOfSuggestion.item(s);
                if (firstSuggestionNode.hasAttributes()) {
                	Node dataNode = firstSuggestionNode.getAttributes().getNamedItem("data");
                	//System.out.println(dataNode.getNodeValue());
                	result += "\"" +dataNode.getNodeValue() + "\",";
                }
            }
        } 
        catch(Exception e)
        {
        	e.printStackTrace();
        }
        finally { 
        }
		

		if(result.length() >0){
			result = result.substring(0,result.length()-1);
		}
		return result;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		process(request,response);
	}
	
	private void googleAutoComplete(String name) {
		URL url;
		try {
			url = new URL("http://www.google.com/complete/search?output=toolbar&q=" + name);
		    Reader reader = new InputStreamReader(new BufferedInputStream(url.openStream())); 
		    int c; 
		    String resp = "";
		    while ((c = reader.read()) != -1) { 
		           resp += (char)c;
		    } 
		    reader.close(); 
		    String[] respArr = resp.split(",");
		    String exchangeRate = respArr[1].replace("rhs: \"", "");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}

}
